package example.controller;

import example.utils.JwtUtil;
import example.utils.ResultData;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/loginController")
@Api(value = "账号管理", description = "账号管理")
public class LoginController {

    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("/login")
    @ApiOperation(value = "用户登陆", notes = "用户登录")
    public ResultData login(String loginName, String password, HttpServletRequest request) throws Exception {
        Map<String, Object> map = new HashMap<>();
        String token = jwtUtil.createJWT(loginName, "张三", "admin");
        String refToken = jwtUtil.createJWT(loginName, "张三", "admin");
        Object roles = jwtUtil.parseJWT(token).get("roles");
        redisTemplate.opsForValue().set(token, refToken, 1, TimeUnit.MINUTES);
        map.put("token", token);
        map.put("role", roles);
        return ResultData.ok(map);
    }

    /*@PostMapping("/haveAdmin/{index}")
    @ApiOperation(value = "验证权限",notes = "验证权限")
    public Map<String, List<Integer>> haveAdmin(@PathVariable Integer index, HttpServletRequest request) throws Exception {
        Map<String, List<Integer>> map = new HashMap<>();
        List<Integer> list_old = new ArrayList<>();
        List<Integer> list_new = new ArrayList<>();

        String token = request.getHeader("Authorization");
        if("".equals(token) || token == null){
            map.put("权限不足", list_new);
            return map;
        }
        System.out.println(token);
        Claims claims = jwtUtil.parseJWT(token);
        Object roles = claims.get("roles");
        System.out.println("roles:  " + roles);

        list_old.add(1);
        list_old.add(2);
        list_old.add(3);
        list_old.add(4);
        list_old.add(5);
        list_old.add(6);
        list_old.add(7);
        list_old.add(8);
        list_old.add(9);
        list_old.add(10);
        list_new.addAll(list_old);
        list_new.remove(index);
        map.put("list_old", list_old);
        map.put("list_new", list_new);
        return map;
    }*/


    @RequestMapping("/haveAdmin/{index}")
    @ApiOperation(value = "验证权限", notes = "验证权限")
    public ResultData haveAdmin(@PathVariable Integer index, HttpServletRequest request) {
        Claims claims = (Claims) request.getAttribute("loginUser");
        return ResultData.ok(claims);
    }
}
